package com.zbkj.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.admin.boot.redisson.command.Redis;
import com.zbkj.admin.constants.SmsConstants;
import com.zbkj.admin.mapper1.EbUserMapper;
import com.zbkj.admin.model.system.SystemUserLevel;
import com.zbkj.admin.model.user.User;
import com.zbkj.admin.model.user.UserExperienceRecord;
import com.zbkj.admin.model.user.UserIntegralRecord;
import com.zbkj.admin.page.CommonPage;
import com.zbkj.admin.pojo.*;
import com.zbkj.admin.request.ArraignApplyRequest;
import com.zbkj.admin.request.CardSecretSearchRequest;
import com.zbkj.admin.request.PageParamRequest;
import com.zbkj.admin.result.CommonResult;
import com.zbkj.admin.response.*;
import com.zbkj.admin.service.*;
import com.zbkj.admin.front.service.UserCenterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 用户 -- 用户中心
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/front/user/center")
@Tag(name = "用户中心控制器")
public class UserCenterFrontController {


    @Autowired
    private UserCenterService userCenterService;
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private EbUserRelationshipService userRelationshipService;
    @Autowired
    private Redis redis;
    @Autowired
    private EbDividendArraignService ebDividendArraignService;
    @Autowired
    private EbDividendConfigService ebDividendConfigService;
    @Autowired
    private EbUserMapper ebUserMapper;

    @Operation(summary = "身份证保存")
    @PostMapping("/identity")
    public CommonResult<Boolean> identity(@RequestBody User user) {
//        smsService.checkValidateCode(SmsConstants.VERIFICATION_CODE_SCENARIO_LOGIN, user.getPhone(), user.getCode());
        User info = userService.getInfo();
        user.setId(info.getId());
        if (StrUtil.isNotBlank(user.getIdentityUrl()) && StrUtil.isNotBlank(user.getIdentityUrl1())) {
            user.setIdentityUrl(String.join(",", user.getIdentityUrl(), user.getIdentityUrl1()));
        }
        EbUserEntity ebUserEntity = BeanUtil.copyProperties(user, EbUserEntity.class);
        ebUserMapper.update(ebUserEntity);
        return CommonResult.success(true);
    }

    public static boolean checkLuhn(String cardNo) {
        int sum = 0;
        boolean alternate = false;
        for (int i = cardNo.length() - 1; i >= 0; i--) {
            int n = Integer.parseInt(cardNo.substring(i, i + 1));
            if (alternate) {
                n *= 2;
                if (n > 9) n = (n % 10) + 1;
            }
            sum += n;
            alternate = !alternate;
        }
        return (sum % 10 == 0);
    }

    @Operation(summary = "获取个人中心详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<UserCenterResponse> getUserCenterInfo() {
        return CommonResult.success(userCenterService.getUserCenterInfo());
    }

    @Operation(summary = "我的粉丝(下线)")
    @RequestMapping(value = "/fans", method = RequestMethod.GET)
    public CommonResult<PageInfo<?>> fans(PageParamRequest pageParamRequest) {
        return CommonResult.success(userCenterService.fans(pageParamRequest));
    }

    @Operation(summary = "粉丝订单")
    @RequestMapping(value = "/fansOrder", method = RequestMethod.GET)
    public CommonResult<PageInfo<?>> fansOrder(PageParamRequest pageParamRequest) {
        return CommonResult.success(userCenterService.fansOrder(pageParamRequest));
    }

    @Operation(summary = "我的上级信息")
    @RequestMapping(value = "/userGoOnline", method = RequestMethod.GET)
    public CommonResult<User> userGoOnline() {
        User info = userService.getInfo();
        EbUserRelationshipEntity one = userRelationshipService.getOne(userRelationshipService.from()
                .where(EbUserRelationshipEntity::getUid).eq(info.getId()));
        if (Objects.isNull(one)) {
            return CommonResult.success(new User());
        }
        return CommonResult.success(userService.getById(one.getPId()));
    }

    @Operation(summary = "我的推广")
    @RequestMapping(value = "/my/promotion", method = RequestMethod.GET)
    public CommonResult<UserMyPromotionResponse> getMyPromotion() {
        return CommonResult.success(userCenterService.getMyPromotion());
    }

    @Operation(summary = "会员等级列表")
    @RequestMapping(value = "/user/level/grade", method = RequestMethod.GET)
    public CommonResult<List<SystemUserLevel>> getUserLevelList() {
        return CommonResult.success(userCenterService.getUserLevelList());
    }

    @Operation(summary = "我的积分")
    @RequestMapping(value = "/my/integral", method = RequestMethod.GET)
    public CommonResult<UserMyIntegralResponse> getMyIntegral() {
        return CommonResult.success(userCenterService.getMyIntegral());
    }

    @Operation(summary = "积分记录")
    @RequestMapping(value = "/integral/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserIntegralRecord>> getIntegralList(@Validated PageParamRequest pageParamRequest) {
        return CommonResult.success(CommonPage.restPage(userCenterService.getUserIntegralRecordList(pageParamRequest)));
    }

    /**
     * V1.2 废弃
     */
    @Deprecated
    @Operation(summary = "经验记录")
    @RequestMapping(value = "/experience/expList", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserExperienceRecord>> getExperienceList(@Validated PageParamRequest pageParamRequest) {
        return CommonResult.success(CommonPage.restPage(userCenterService.getUserExperienceList(pageParamRequest)));
    }

    @Operation(summary = "我的账户")
    @RequestMapping(value = "/my/account", method = RequestMethod.GET)
    public CommonResult<UserMyAccountResponse> getMyAccount() {
        return CommonResult.success(userCenterService.getMyAccount());
    }

    @Operation(summary = "余额记录")
    @RequestMapping(value = "/balance/record", method = RequestMethod.GET)
//    @ApiImplicitParam(name = "type", value = "记录类型：all-全部，expenditure-支出，income-收入，recharge-充值", required = true)
    public CommonResult<CommonPage<UserBalanceRecordMonthResponse>> userBalanceRecord(
            @RequestParam(name = "type") String type,
            @RequestParam(name = "flowingWaterType", required = false) String flowingWaterType,
            @ModelAttribute PageParamRequest pageRequest) {
        return CommonResult.success(CommonPage.restPage(userCenterService.getUserBalanceRecord(type, flowingWaterType, pageRequest)));
    }

    @Operation(summary = "订单头部数量")
    @RequestMapping(value = "/order/num", method = RequestMethod.GET)
    public CommonResult<OrderCenterNumResponse> getUserCenterOrderNum() {
        return CommonResult.success(userCenterService.getUserCenterOrderNum());
    }

    @Operation(summary = "足迹记录")
    @RequestMapping(value = "/browse/record", method = RequestMethod.GET)
    public CommonResult<List<UserBrowseRecordDateResponse>> userBrowseRecord() {
        return CommonResult.success(userCenterService.getUserBrowseRecord());
    }

    @Operation(summary = "我的经验页")
    @RequestMapping(value = "/my/exp", method = RequestMethod.GET)
    public CommonResult<UserMyExpResponse> getMyExp() {
        return CommonResult.success(userCenterService.getMyExp());
    }

    @Operation(summary = "我的经验记录列表")
    @RequestMapping(value = "/my/exp/record/list", method = RequestMethod.GET)
    public CommonPage<UserExperienceRecordMonthResponse> findMyExpRecordList(PageParamRequest pageRequest) {
        return CommonPage.restPage(userCenterService.findMyExpRecordList(pageRequest));
    }

    @Operation(summary = "签到经验记录")
    @RequestMapping(value = "/sign/experience/expList", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserExperienceRecord>> getSignExperienceList(@Validated PageParamRequest pageParamRequest) {
        return CommonResult.success(CommonPage.restPage(userCenterService.getUserSignExperienceList(pageParamRequest)));
    }

    @PostMapping("/submitArraignApply")
    @Operation(summary = "用户-发起提现申请")
    public R<Boolean> submitArraignApply(@RequestBody @Validated ArraignApplyRequest request) {
        // 设置类型为用户
        request.setType("1");
        Boolean bool = ebDividendArraignService.submitArraignApply(request);
        if(!bool){
            return R.fail("");
        }
        return R.success();
    }


    /**
     * 查询用户提现记录
     * */
    @GetMapping("/getUserArraignApplyList")
    @Operation(summary = "查询用户提现记录")
    public R<PageInfo<EbDividendArraignEntity>> getUserArraignApplyList(@Validated PageParamRequest request) {
        return R.success(ebDividendArraignService.getUserArraignApplyList(request));
    }


    @GetMapping("/getHandFee")
    @Operation(summary = "获取提现税率")
    public R<BigDecimal> getHandFee() {
        return R.success(ebDividendConfigService.getHandFee());
    }
}



